<template>
  <div>
    <el-container style="background: #f5f7f9;">
      <el-header style="background: #fff;padding: 12px 12px;height:auto;">
        <div>
          <el-form :model="queryData" :inline="true" size="small">
            <el-form-item label="产品">
              <el-select v-model="queryData.channelId" clearable filterable>
                <el-option v-for="(item, i) in channelOptions" :key="i" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户">
              <el-select v-model="queryData.orgOwner" clearable filterable>
                <el-option v-for="(d, i) in customerOptions" :key="i" :label="d.orgOwnerName" :value="d.orgOwner" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单号">
              <el-input v-model="queryData.orderId" :rows="1" style="width: 280px;" type="textarea" placeholder="多个单号用回车分割" />
            </el-form-item>
            <el-form-item label="第一次录入成本时间">
              <el-date-picker
                v-model="queryData.createAtRange"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchData()">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main style="margin-top: 15px; background: #fff;padding: 12px 16px 0 16px;height: 100%;">
        <div style="height: 100%;display: flex;">
          <el-button size="small" @click="download">导出</el-button>
        </div>
        <el-table ref="multipleTable" :data="tableData" stripe tooltip-effect="dark" border :max-height="tableHeight" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="orderNumber" fixed label="订单号" />
          <el-table-column prop="orgOwnerName" label="客户" />
          <el-table-column prop="channelName" label="产品" />
          <el-table-column prop="totalChargePrepaid" label="预收" />
          <el-table-column prop="totalCostPrepaid" label="预付" />
          <el-table-column prop="totalCharge" label="实收" />
          <el-table-column prop="totalCost" label="实付" />
          <el-table-column prop="profit" label="利润" />
          <el-table-column prop="createAt" label="下单时间" />
          <el-table-column prop="totalWeight" label="打单重量" />
          <el-table-column prop="totalCarton" label="箱数" />
          <el-table-column prop="firstSupplementCostAt" label="第一次录入成本时间" />
        </el-table>
      </el-main>
      <el-footer style="padding:0;background: #fff;">
        <div style="text-align: right; padding-top: 10px;">
          <!-- 分页 -->
          <el-pagination background :current-page="queryData.currentPage" :page-sizes="[50, 100, 200, 300, 400]" :page-size="queryData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" style="float: right;" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import request from '@/utils/request'
export default {
  components: {},
  data() {
  return {
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      queryData: {
        pageSize: 50,
        currentPage: 0,
        orgOwner: '',
        orderId: '',
        customerRef: '',
        channelId: '',
        status: 'all',
        createAtRange: [],
        firstSupplementCost: true
      },
      tableData: [],
      multipleSelection: [],
      currentPage: 1, // 分页
      total: 0
    }
  },
  computed: {
    tableHeight() {
      return document.documentElement.clientHeight - 280
    },
    ...mapState(//
      {
        paymentTerm: state => state.base.paymentTerm,
        customerOptions: state => state.base.customerOptions,
        channelOptions: state => state.base.channelOptions,
        profile: state => state.user,
        orderStatusOptions: state => state.base.orderStatusOptions
      }
    ),
    isOrgOwner() {
      return this.profile.orgOwner
    }
  },
  created() {
    this.queryOrder()
  },
  methods: {
    download() {
      const orderNumber = []
      this.multipleSelection.forEach(e => {
        orderNumber.push(e.orderNumber)
      })
      this.queryData.orderId = orderNumber.join('\n')
      if (this.queryData.orgOwner || this.queryData.orderId ||
      this.queryData.customerRef || this.queryData.channelId ||
      (this.queryData.createAtRange && this.queryData.createAtRange.length === 2)) {
        request({
          url: 'order/download',
          data: this.queryData,
          method: 'post'
        }).then(res => {
          this.queryData.orderId = ''
          if (res.success) {
            const link = document.createElement('a')
            const array = this.base64ToUint8Array(res.data)
            const blob = new Blob([array])
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', `订单明细.xlsx`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        })
      } else {
        this.$message({
          message: '请先选择条件',
          type: 'error'
        })
      }
    },
    base64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4)
      const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/')
      const rawData = window.atob(base64)
      const outputArray = new Uint8Array(rawData.length)
      for (let i = 0; i < rawData.length; ++i) {
          outputArray[i] = rawData.charCodeAt(i)
      }
      return outputArray
    },
    searchData() {
      this.queryData.currentPage = 1
      this.queryOrder()
    },
    // 搜索
    queryOrder() {
      request({
        url: 'order/query',
        data: this.queryData,
        method: 'post'
      }).then(res => {
        if (res.success) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    // 多选按钮
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 分页
    handleSizeChange(val) {
      this.queryData.currentPage = 1
      this.queryData.pageSize = val
      this.queryOrder()
    },
    handleCurrentChange(val) {
      this.queryData.currentPage = val
      this.queryOrder()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
<style>
.red {
  color: red;
  /* background: indianred; */
}
</style>
